import {Native} from "./native.js"

/**
 * 获取位置
 * @static
 * @version 2
 * @author GuoHua Liu
 * @copyright Copyright © 2019 GuoHua Liu. All rights reserved.
 */
class location {
    /**
     * @private
     * @param {string} name
     * @param {function} onevent
     * @param {*} context
     */
    static addObserver(name, onevent, context) {
        Native.getInstance().addObserver("location/" + name, onevent, context)
        return this;
    }

    /**
     * @private
     * @param {string} name
     * @param {function} onevent
     */
   static removeObserver(name, onevent) {
        Native.getInstance().delObserver("location/" + name, onevent)
        return this;
    }

    /**
     * @callback LocationUpdateObserver
     * @param {{name:string,data:{locations:Array<{latitude:number,longitude:number}>}}} event
     */

    /**
     * 添加观察者：位置更新
     * @since 2
     * @param {LocationUpdateObserver} onevent
     * @param {*} context
     */
    static addUpdateObserver(onevent, context=null) {
        this.addObserver("update", onevent, context)
        return this;
    }

    /**
     * 删除addUpdateObserver注册的观察者
     * @since 2
     * @param {LocationUpdateObserver|null} onevent
     */
    static removeUpdateObserver(onevent = null) {
        this.removeObserver("update", onevent)
        return this;
    }

    /**
     * 在定位之前，需要先请求授权
     * @requires {Promise} 错误码:
     * - -1 环境不支持
     * - 其他 未知错误
     */
    static requestAuthorization() {
        return new Promise((resolve,reject)=>{
            if (Native.getInstance().isHos()) {
                Native.getInstance().callNative("location", {method:"requestAuthorization"}, true, resolve, reject);
            } else {
                reject({errMsg:"当前环境不支持", errCode:-1})
            }
        })
    }

    /**
     * 发起定位请求
     */
    static requestLocation() {
        Native.getInstance().callNative("location", {method:"requestLocation"});
    }

    /**
     * 实时定位
     */
    static startUpdatingLocation() {
        Native.getInstance().callNative("location", {method:"startUpdatingLocation"});
    }

    /**
     * 停止实时定位。
     */
    static stopUpdatingLocation() {
        Native.getInstance().callNative("location", {method:"stopUpdatingLocation"});
    }

}

export {location}

